package com.tanhua.soul.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.ScoreApi;
import com.tanhua.dubbo.server.pojo.Score;
import com.tanhua.soul.enums.SexEnum;
import com.tanhua.soul.mapper.*;
import com.tanhua.soul.pojo.*;
import com.tanhua.soul.utils.UserThreadLocal;
import com.tanhua.soul.vo.QuestionnaireVo;
import com.tanhua.soul.vo.QuestionsVo;
import com.tanhua.soul.vo.ResultVo;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: Shanhai
 * Never say Never
 * @Date: 2020/12/14 15:30
 */
@Service
public class SoulService {
    @Reference( version = "1.0.0" )
    private ScoreApi scoreApi;

    @Autowired
    private OptionsMapper optionsMapper;

    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private QuestionnaireQuestionsMapper questionnaireQuestionsMapper;

    @Autowired
    private QuestionsOptionsMapper questionsOptionsMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;



    /**
     * 查询问卷列表
     * @return
     */
    public List<QuestionnaireVo> listQuestionnaire() {

        User user = UserThreadLocal.get();
        Long userId = user.getId();




        //三个返还给前端的对象
        List<QuestionnaireVo> questionnaireVos = new ArrayList<>();

        //从数据库查询出所用的信息添加到QuestionnaireVo对象中
        List<Questionnaire> questionnaireList = questionnaireMapper.selectAll();

        //TODO 遍历所有的试卷
        for (Questionnaire questionnaire : questionnaireList) {
            //获取 试卷id
            Integer quid = questionnaire.getQuid();

            QueryWrapper<QuestionnaireQuestions> queryWrapper = new QueryWrapper();
            queryWrapper.eq("quid",quid);
            List<QuestionnaireQuestions> questionnaireQuestionsList = questionnaireQuestionsMapper.selectList(queryWrapper);

            //对应试卷的 所有题目id
            List<Integer> questionsIdList = new ArrayList<>();

            for (QuestionnaireQuestions questionnaireQuestions : questionnaireQuestionsList) {
                questionsIdList.add(questionnaireQuestions.getQid());
            }

            QueryWrapper<Questions> questionsQueryWrapper = new QueryWrapper<>();
            questionsQueryWrapper.in("qid",questionsIdList);
            List<Questions> questionsList = questionsMapper.selectList(questionsQueryWrapper);

            List<QuestionsVo> questionsVoList = new ArrayList<>();

            // TODO 遍历所有的题目
            for (Questions questions : questionsList) {



                //题目id
                Integer qid = questions.getQid();

                QueryWrapper<QuestionsOptions> questionsOptionsQueryWrapper = new QueryWrapper<>();
                questionsOptionsQueryWrapper.eq("qid",qid);
                List<QuestionsOptions> questionsOptionsList = questionsOptionsMapper.selectList(questionsOptionsQueryWrapper);

                //对应题目的所有选项id
                List<Integer> optionsIdList = new ArrayList<>();

                for (QuestionsOptions questionsOptions : questionsOptionsList) {
                    optionsIdList.add(questionsOptions.getOid());
                }

                //所有的选项
                //TODO 遍历所有的选项
                QueryWrapper<Options> optionsQueryWrapper = new QueryWrapper<>();
                optionsQueryWrapper.in("oid",optionsIdList);
                List<Options> optionsList = optionsMapper.selectList(optionsQueryWrapper);

                //封装QuestionsVo
                QuestionsVo questionsVo = new QuestionsVo();
                questionsVo.setId(qid);
                questionsVo.setQuestion(questions.getQuestion());
                questionsVo.setOptions(optionsList);
                //装填 questionsVoList
                questionsVoList.add(questionsVo);
            }


            //封装 试卷类;
            QuestionnaireVo questionnaireVo = new QuestionnaireVo();
            questionnaireVo.setId(quid);
            questionnaireVo.setName(questionnaire.getName());
            questionnaireVo.setCover(questionnaire.getCover());
            questionnaireVo.setLevel(questionnaire.getLevel());
            questionnaireVo.setStar(questionnaire.getStar());
            questionnaireVo.setQuestions(questionsVoList);
            questionnaireVo.setIsLock(1);

            questionnaireVos.add(questionnaireVo);
        }


        int shuliang = -1;
/*        Map<String,String> map = new TreeMap<>();
        int shuliang = map.size();*/
        // param : userId -->
        // return map --> int map(shuliang)
        // shuliang <=0 --> 0 1 1
        // ==1 --> 0 0 1
        // >=2 --> 0 0 0
        TreeMap<String, Integer> map = this.scoreApi.selectByUserId(Long.valueOf(userId).intValue());
        if( map == null ){
            Score score = new Score();
            score.setLevel("初级");
            score.setUserId(Long.valueOf(userId).intValue());
            this.scoreApi.save(score);
        }else{
            shuliang = map.size();
        }
        if( shuliang<= 0 ){
                //初级
                for (QuestionnaireVo questionnaireVo : questionnaireVos) {
                    if( questionnaireVo.getStar() == 2 ){
                        questionnaireVo.setIsLock(0);
                    }
                }
            }else if( shuliang == 1 ){
                //中级
                for (QuestionnaireVo questionnaireVo : questionnaireVos) {
                    if( questionnaireVo.getStar() <= 3 ){
                        questionnaireVo.setIsLock(0);
                    }
                }
            }else if( shuliang >= 2 ){
                //高级
                for (QuestionnaireVo questionnaireVo : questionnaireVos) {
                    if( questionnaireVo.getStar() <= 5 ){
                        questionnaireVo.setIsLock(0);
                    }
                }
            }


        return questionnaireVos;
    }

    public String getReportId( List<Integer> questionIds, List<Integer> optionIds) {
        User user = UserThreadLocal.get();
        Long id = user.getId();


        int count=0;
        int i=0;
        for (Integer questionId : questionIds) {
            Integer optionId = optionIds.get(i);
            i++;
            QueryWrapper<QuestionsOptions> queryWrapper=new QueryWrapper();
            queryWrapper.eq("qid",questionId).eq("oid", optionId);
            QuestionsOptions questionsOption = this.questionsOptionsMapper.selectOne(queryWrapper);
            Integer score = questionsOption.getScore();
            count+=score;


        }

        //获取问卷id
        QueryWrapper<QuestionnaireQuestions> queryWrapper=new QueryWrapper();
        queryWrapper.eq("qid",questionIds.get(0));
        Integer quid = questionnaireQuestionsMapper.selectOne(queryWrapper).getQuid();

        //通过问卷id查询问卷等级
        QueryWrapper<Questionnaire> queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("quid",quid);
        String level = questionnaireMapper.selectOne(queryWrapper1).getLevel();

        //查询性格类型
        QueryWrapper<Report> queryWrapper2=new QueryWrapper();
        queryWrapper2.ge("max_score",count).le("min_score",count);
        String character = reportMapper.selectOne(queryWrapper2).getCharacterTb();


        //存储用户得分和性格
        Score score=new Score();
        score.setUserId(Integer.parseInt(id.toString()));
        score.setScore(count);
        score.setLevel(level);
        score.setCharacter(character);

        //进行判断：是否为重复测试的人员
        TreeMap<String, Integer> map = this.scoreApi.selectByUserId(Long.valueOf(id).intValue());
        if( map == null || map.size() ==0 ){
            //非重复测试人员
            this.scoreApi.save(score);
        }else{
            //重复测试人员
            this.scoreApi.updateByUserIdAndLevel( score,id,level );
        }

        String levelnumber = "";
        if( StringUtils.equals(level, "初级") ){
            levelnumber = "1";
        }else if( StringUtils.equals(level, "中级") ){
            levelnumber = "2";
        }else if( StringUtils.equals(level, "高级") ){
            levelnumber = "3";
        }


        String reportId=levelnumber+","+count;
        return reportId;
    }

    /**
     * 灵魂测试结果
     *
     * @param reportId
     * @return
     */
    public ResultVo testResultService(String reportId) {
        //如果reportId为空，返回null
        if (null == reportId) {
            return null;
        }

        //获取user信息
        User user = UserThreadLocal.get();
        Long userId = user.getId();

        String[] split = reportId.split(",");
        String type = split[0];

        String level = "";
        if( StringUtils.equals(type.trim(), "1") ){
            level = "初级";
        }else if( StringUtils.equals(type.trim(), "2") ){
            level = "中级";
        }else if( StringUtils.equals(type.trim(), "3") ){
            level = "高级";
        }

        //查表mongoDb
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("level").is(level));
        Score scoreOne = this.mongoTemplate.findOne(query, Score.class);
        /*Score scoreOne = new Score();
        scoreOne.setScore(50);*/
        //根据性格类型获取报告类型的性格类型和性格描述和封面
        Integer score = scoreOne.getScore();

        QueryWrapper<Report> reportWrapper = new QueryWrapper<>();
        reportWrapper.ge("max_score", score).le("min_score", score);
        Report report = reportMapper.selectOne(reportWrapper);

        ResultVo resultVo = new ResultVo();
        resultVo.setConclusion(report.getCharacterTb() + ":" + report.getCharacterInfo());
        resultVo.setCover(report.getCover());
        ArrayList<Dimensions> dmList = new ArrayList<>();
        Dimensions dm = new Dimensions();
        dm.setKey("外向");
        dm.setValue("99%");
        dmList.add(dm);
        dm = new Dimensions();
        dm.setKey("内向");
        dm.setValue("10%");
        dmList.add(dm);
        dm = new Dimensions();
        dm.setKey("开朗");
        dm.setValue("11%");
        dmList.add(dm);
        dm = new Dimensions();
        dm.setKey("活泼");
        dm.setValue("12%");
        dmList.add(dm);
        resultVo.setDimensions(dmList);

        //获取当前登录信息的性别 -- mysql userInfo表
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        UserInfo info = userInfoMapper.selectOne(wrapper);
        System.out.println("info = " + info);
        SexEnum mySex = info.getSex();

        SimilarYouVo slVo = new SimilarYouVo();
        ArrayList<SimilarYouVo> similarYouList = new ArrayList<>();

        //根据分数查询相似的人
        Query query2 = Query.query(Criteria.where("level").is(level));



        List<Score> scoreList = this.mongoTemplate.find(query2, Score.class);

        for (Score uList : scoreList) {
            Integer user_id = uList.getUserId();

            QueryWrapper wrapper2 = new QueryWrapper();
            wrapper2.eq("user_id", user_id);
            UserInfo userInfo = userInfoMapper.selectOne(wrapper2);
            SexEnum sex = userInfo.getSex();
            //如果性别和当前用户不一样，塞值
            if (sex != mySex) {
                slVo.setId(user_id);
                slVo.setAvatar(userInfo.getLogo());
                similarYouList.add(slVo);
            }
        }
        resultVo.setSimilarYou(similarYouList);

        return resultVo;
    }
}
